package weaver.interfaces.zjj.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.axis.encoding.Base64;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import weaver.alioss.AliOSSObjectManager;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.file.AESCoder;
import weaver.general.Util;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.zip.ZipInputStream;

/**
 * @Title: ecology-idea
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2022-06-23
 * @Description: ${description}
 * @ModifyLog:
 **/

public class ZjjUtil {

    public static void main(String[] args) throws Exception{
        String remark = "经核实，该小区正在进行维修。开发和施工单位之间已达成一致，维修过渡方案已有。因疫情等不可抗力产生的延迟应属于可理解范围。赔偿问题不在我局协调范围内，请自行与开发商协商或依法向法院提起诉讼，维护自身合法权益。诉求人未留联系方式，无法与其联系。";
        JSONObject params = new JSONObject();
        params.put( "IdentityGuid", "Epoint_WebSerivce_**##0601" );
        params.put( "TaskGuid", "20220715162406015_f30bb5dd08f5480a93c95eda7db77256");
        params.put( "MessageItemGuid", "20220715162405953_b2d35fe083764e7ba623fdb34c0f62f2");
        params.put( "FeedBackContent",remark);
        params.put( "PromiseDate", "2022-07-24");
        params.put( "UserGuid", "186566dd-5baf-4789-b5ea-52328a029ac3");
        JSONObject returnJson =  FeedBack_Opinion(params);
        String Description = returnJson.getString( "Description" );
        System.out.println(new String(Description.getBytes(), "UTF-8"));
       /* String filePath = "F:\\download\\Java开发手册（黄山版）.pdf";
        String fileName = "Java开发手册（黄山版）.pdf";
        File file = new File(filePath);
        byte [] bytes = Base64Util.readBytes(file);
        JSONObject returnJson = UploadThirdFile(fileName,bytes);
        System.out.println(returnJson);*/
    }

    public static String stripHtml(String content) {
        content = content.replaceAll( "\\n","" );
        // <p>段落替换为换行
        content = content.replaceAll("<p .*?>", "");
        // <br><br/>替换为换行
        content = content.replaceAll("<br\\s*/?>", "");
        // 去掉其它的<>之间的东西
        content = content.replaceAll("\\<.*?>", "");
        return content;
    }
    /***
     *
     * @param url
     * @param soapXml
     * @param soapAction
     * @return
     * @throws Exception
     */
    public static String doPostSoapFile(String url, String soapXml, String soapAction) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost( url );
        //设置请求和传输超时时间
        String returnResult = "";
        CloseableHttpResponse response = null;
        try {
            httpPost.setHeader( "Content-Type", "text/xml;charset=UTF-8" );
            httpPost.setHeader( "SOAPAction", soapAction );
            StringEntity data = new StringEntity( soapXml );
            httpPost.setEntity( data );
            response = closeableHttpClient.execute( httpPost );
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                String result = EntityUtils.toString( httpEntity, "UTF-8" );
                if (!"".equals( result )) {
                    returnResult = result ;
                }
            }

        } catch (Exception e) {
            System.out.println( "e：" + e );
        }
        return returnResult;
    }
    /**
     * @Description: 附件上传调用接口
     * @Param: [paramJson]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2022/6/20
     */
    public static JSONObject UploadThirdFile(String fileName,byte[] bytes) throws Exception{
        JSONObject returnJson = new JSONObject(  );
        String wsdl = "http://2.18.220.226/12345/WebService/FileService.asmx";
        String soapAction = "http://tempuri.org/UploadThirdFile2";
        String Header_beg = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/>";
        String Header_end = "</soapenv:Envelope>";
        String Body_beg = "<soapenv:Body>";
        String Body_end = "</soapenv:Body>";
        String Method_beg = "<tem:UploadThirdFile2>";
        String Method_end = "</tem:UploadThirdFile2>";
        String body = "<tem:caseSourceName>WGH</tem:caseSourceName>" +
                "<tem:sessionID>V0dIMTg=</tem:sessionID>" +
                "<tem:caseSourceID>18</tem:caseSourceID>" +
                "<tem:fileName>"+ URLEncoder.encode(fileName, "UTF-8")+"</tem:fileName>" +
                "<tem:bytes>"+ Base64.encode(bytes)+"</tem:bytes>";
        StringBuilder templateXML = new StringBuilder( Header_beg );
        templateXML.append( Body_beg );
        templateXML.append( Method_beg );
        templateXML.append( body );
        templateXML.append( Method_end );
        templateXML.append( Body_end );
        templateXML.append( Header_end );
        String xml = templateXML.toString();
        String message = doPostSoapFile( wsdl, xml, soapAction );
        Document xmlDocument = DocumentHelper.parseText( message );
        if (xmlDocument != null) {
            Element rootElement = xmlDocument.getRootElement();
            Element Body = rootElement.element( "Body" );
            Element UploadThirdFile2Response = Body.element( "UploadThirdFile2Response" );
            Element UploadThirdFile2Result = UploadThirdFile2Response.element( "UploadThirdFile2Result" );
            returnJson.put("FileNumber",UploadThirdFile2Result.getTextTrim());
        }
        return returnJson;
    }

    /**
     * @Description: 反馈处理意见
     * @Param: [paramJson]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2022/6/20
     */
    public static JSONObject FeedBack_Opinion(JSONObject paramJson) throws Exception{
        JSONObject returnJson = new JSONObject();
        String method = "FeedBack_Opinion";
        String param = "xmlTaskInfo";
        String message = InvokeHandle( paramJson, method, param );
        Document xmlDocument = DocumentHelper.parseText( message );
        if (xmlDocument != null) {
            Element rootElement = xmlDocument.getRootElement();
            Element DATA = rootElement.element( "DATA" );
            Element ReturnInfo = DATA.element( "ReturnInfo" );
            String Status = ReturnInfo.element( "Status" ).getTextTrim();
            String Description = ReturnInfo.element( "Description" ).getTextTrim();
            returnJson.put( "Status", Status );
            returnJson.put( "Description", Util.null2String( Description ) );
        }
        return returnJson;
    }

    /**
     * @Description: 反馈处理意见带附件
     * @Param: [paramJson]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2022/6/20
     */
    public static JSONObject FeedBack_Opinion2(JSONObject paramJson) throws Exception{
        JSONObject returnJson = new JSONObject();
        String method = "FeedBack_Opinion2";
        String param = "xmlTaskInfo";
        String message = InvokeHandle( paramJson, method, param );
        Document xmlDocument = DocumentHelper.parseText( message );
        if (xmlDocument != null) {
            Element rootElement = xmlDocument.getRootElement();
            Element DATA = rootElement.element( "DATA" );
            Element ReturnInfo = DATA.element( "ReturnInfo" );
            String Status = ReturnInfo.element( "Status" ).getTextTrim();
            String Description = ReturnInfo.element( "Description" ).getTextTrim();
            returnJson.put( "Status", Status );
            returnJson.put( "Description", Util.null2String( Description ) );
        }
        return returnJson;
    }

    /**
     * @Description: 通用调用接口
     * @Param: [paramJson]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2022/6/20
     */
    public static String InvokeHandle(JSONObject paramJson, String method, String param) {
        String wsdl = "http://2.18.220.226/12345/WebService/_2345Service.asmx";
        String soapAction = "http://tempuri.org/" + method;
        String Header_beg = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\"><soapenv:Header/>";
        String Header_end = "</soapenv:Envelope>";
        String Body_beg = "<soapenv:Body>";
        String Body_end = "</soapenv:Body>";
        String Method_beg = "<tem:" + method + ">";
        String Method_end = "</tem:" + method + ">";
        String headXML = "&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;";
        String xmlUserGuid_beg = "<" + param + ">";
        String xmlUserGuid_end = "</" + param + ">";
        StringBuilder body = new StringBuilder( "&lt;paras&gt;" );
        paramJson.forEach( (key, value) -> {
            body.append( "&lt;" + key + "&gt;" + value + "&lt;/" + key + "&gt;" );
        } );
        body.append( "&lt;/paras&gt;" );
        StringBuilder templateXML = new StringBuilder( Header_beg );
        templateXML.append( Body_beg );
        templateXML.append( Method_beg );
        templateXML.append( xmlUserGuid_beg );
        templateXML.append( headXML );
        templateXML.append( body );
        templateXML.append( xmlUserGuid_end );
        templateXML.append( Method_end );
        templateXML.append( Body_end );
        templateXML.append( Header_end );
        String xml = templateXML.toString();
        String message = doPostSoap( wsdl, xml, soapAction );
        return message;
    }

    /***
     *
     * @param url
     * @param soapXml
     * @param soapAction
     * @return
     * @throws Exception
     */
    public static String doPostSoap(String url, String soapXml, String soapAction) {
        String returnResult = "";
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try{
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type","text/xml;charset=UTF-8");
            connection.setRequestProperty( "SOAPAction", soapAction );
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //1.获取URLConnection对象对应的输出流
            //out = new PrintWriter(connection.getOutputStream());
            //2.中文有乱码的需要将PrintWriter改为如下
            out=new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            // 发送请求参数
            out.write(soapXml);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if (!"".equals( result )) {
                System.out.println(result);
                String newresult = result.substring( result.indexOf( "&lt;" ), result.lastIndexOf( "&gt;" ) + 4 );
                returnResult = StringEscapeUtils.unescapeXml( newresult );
            } else {
                returnResult = "接口返回结果为空";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
        return returnResult;
    }

    /**
     * 返回文件流   已经经过脱密、解压
     *
     * @param imageFileId_para
     * @return 文件流
     * @throws Exception
     */
    public static InputStream getInputStreamById(int imageFileId_para) {
        InputStream imagefile = null;
        try {
            RecordSet rs = new RecordSet();
            String sql = "select fileRealPath,isZip,isaesencrypt,aescode,tokenKey,storageStatus  from ImageFile where imageFileId = " + imageFileId_para;
            rs.executeQuery( sql );
            if (rs.next()) {
                String static_fileRealPath = Util.null2String( rs.getString( "fileRealPath" ) );
                String static_isZip = Util.null2String( rs.getString( "isZip" ) );
                int static_isaesencrypt = Util.getIntValue( rs.getString( "isaesencrypt" ), 0 );
                String static_aescode = Util.null2String( rs.getString( "aescode" ) );
                String static_tokenKey = Util.null2String( rs.getString( "tokenKey" ) );
                String static_storageStatus = Util.null2String( rs.getString( "storageStatus" ) );
                boolean isonlyAliOSS = false;
                if (!static_tokenKey.equals( "" ) && static_storageStatus.equals( "1" ) && AliOSSObjectManager.isonlyAliOSS()) {
                    isonlyAliOSS = true;
                }
                if (isonlyAliOSS) {
                    imagefile = weaver.alioss.AliOSSObjectUtil.downloadFile( static_tokenKey );
                } else {
                    if (static_fileRealPath != null && !static_fileRealPath.equals( "" )) {
                        File thefile = new File( static_fileRealPath );
                        if (static_isZip.equals( "1" )) {
                            ZipInputStream zin = new ZipInputStream( new FileInputStream( thefile ) );
                            if (zin.getNextEntry() != null)
                                imagefile = new BufferedInputStream( zin );
                        } else {
                            imagefile = new BufferedInputStream( new FileInputStream( thefile ) );
                        }
                    } else {
                        ConnStatement statement = null;
                        try {
                            statement = new ConnStatement();
                            boolean isoracle = ("oracle").equals( statement.getDBType() );
                            statement.setStatementSql( "select imagefile from ImageFile where imagefileid = " + imageFileId_para );
                            statement.executeQuery();
                            if (statement.next()) {
                                if (isoracle)
                                    imagefile = new BufferedInputStream( statement.getBlobBinary( "imagefile" ) );
                                else imagefile = new BufferedInputStream( statement.getBinaryStream( "imagefile" ) );
                            }
                        } catch (Exception ex) {
                        } finally {
                            try {
                                if (statement != null) statement.close();
                            } catch (Exception ex) {
                            }
                        }
                    }
                    if (static_isaesencrypt == 1) {
                        imagefile = AESCoder.decrypt( imagefile, static_aescode );
                    }

                }
            }


        } catch (Exception ex) {

        }
        return imagefile;
    }

}
